package org.xxpay.pay.channel.qingfeng;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Component;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.util.HtmlUtils;
import org.xxpay.common.util.Util;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.common.util.str.StringUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;

import java.util.Map;


/**
 * @Package org.xxpay.pay.channel.qingfeng
 * @Class: QingfengpayPaymentService.java
 * @Description:
 * @Author leo
 * @Date 2019/5/13 19:02
 * @Version
 **/
@Component
public class QingfengpayPaymentService extends BasePayment {

    private final static String logPrefix = "【庆丰支付】";

    @Override
    public String getChannelName() {
        return QingfengpayConfig.CHANNEL_NAME;
    }


    @Override
    public JSONObject pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        JSONObject retObj;
        switch (channelId) {
            case QingfengpayConfig.CHANNEL_NAME_TYPE:
                retObj = doOrderReq(payOrder);
                break;
            default:
                retObj = buildRetObj(PayConstant.RETURN_VALUE_FAIL, "不支持的渠道[channelId="+channelId+"]");
                break;
        }

        return retObj;
    }

    @Override
    public JSONObject query(PayOrder payOrder) {
        QingfengpayConfig qingfengpayConfig = new QingfengpayConfig(getPayParam(payOrder));

        String queryString = "?sid=%s&cpid=%s&keystr=%s";
        String signTxt = payOrder.getPayOrderId() + qingfengpayConfig.getMchId() + qingfengpayConfig.getPrivateKey();
        String sign = SignUtils.sha256ToBase64(signTxt);
        queryString = String.format(queryString, payOrder.getPayOrderId(), qingfengpayConfig.getMchId(), sign);
        String doOrderQueryUrl = QingfengpayConfig.QUERY_ORDER_URL + queryString;
        _log.info("{}查单请求数据: {}", logPrefix, doOrderQueryUrl);
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.getForObject(doOrderQueryUrl, JSONObject.class);
        _log.info("{}查单http响应：{}", logPrefix, origin.toJSONString());
        // 响应对象
        JSONObject finalRetObj = new JSONObject();
        finalRetObj.put("channelOrderNo", origin.getString("sid"));
        finalRetObj.put("channelObj", origin);
        finalRetObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_SUCCESS);
        // 渠道status值：ok(or nook)，ok：已支付 nook：支付失败
        if(StringUtils.equals(QingfengpayConfig.ASYNC_NOTIFY_STATUS_OK, origin.getString("status"))) {
            finalRetObj.put("status", 2); // 已支付
            return finalRetObj;
        }
        finalRetObj.put("status", 1); // 支付中
        return finalRetObj;
    }

    private JSONObject doOrderReq(PayOrder payOrder) {
        JSONObject retObj = new JSONObject();
        // 如果金额不为正整数
        if((payOrder.getAmount() % 100) > 0) {
            retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
            retObj.put(PayConstant.RESULT_PARAM_ERRDES, "当前渠道订单金额不支持小数");
            return retObj;
        }

        QingfengpayConfig qingfengpayConfig = new QingfengpayConfig(getPayParam(payOrder));
        String orderAmt = Util.conversionYuanAmount(payOrder.getAmount(), 0).toString();
        String signTxt = payOrder.getPayOrderId() + qingfengpayConfig.getMchId() + orderAmt + qingfengpayConfig.getPrivateKey();
        String sign = SignUtils.sha256ToBase64(signTxt);


        Map<String, Object> parameters = Maps.newHashMap();
        parameters.put("sid", payOrder.getPayOrderId());
        parameters.put("cpid", qingfengpayConfig.getMchId());
        parameters.put("value", orderAmt);
        parameters.put("keystr", sign);

        _log.info("{}请求数据：{}", logPrefix, JSON.toJSONString(parameters));
        _log.debug("{}回调地址：{}", logPrefix, payConfig.getNotifyUrl(QingfengpayConfig.CHANNEL_NAME));

        // 将订单更改为支付中
        int result = rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
        _log.info("[{}]更新订单状态为支付中:payOrderId={},channelOrderNo={},result={}", getChannelName(), payOrder.getPayOrderId(), null, result);


        String formTxt = HtmlUtils.form(qingfengpayConfig.getRequestUrl(), HtmlUtils.GET, parameters);

        return buildPayResultOfForm(retObj, payOrder, formTxt);
    }

}
